import {Component, AfterViewInit, OnDestroy} from '@angular/core';
import {Events, IonicPage, PopoverController} from 'ionic-angular';
import {HttphandleProvider} from '../../providers/httphandle/httphandle';
import {LocalstorageProvider} from '../../providers/localstorage/localstorage';
import ECharts from 'echarts';
import {ToastController} from 'ionic-angular';
import { Router } from '@angular/router';
import { NativePageTransitions } from '@ionic-native/native-page-transitions';
import { Tools } from '../../tools/tools';
import { Network } from '@ionic-native/network';
import { ChoselinePage } from '../choseline/choseline'


// "productLineState": "当前无产线开工！",

@IonicPage()
@Component({selector: 'page-line-attendance', templateUrl: 'line-attendance.html'})
export class LineAttendancePage extends Tools implements AfterViewInit,OnDestroy {
  public title: string = '生产监控';
  private AttendandceList = [];
  private ProductionLine = {
    name: '',
    state: false
  };
  private line: any;
  private lineState: boolean;
  private orderOne: any;
  private orderTwo: any;
  private ngAfterViewInitState: boolean;
  private myChart: any;
  private defect: any;
  private titleState: boolean = false;
  private productLineState: boolean = false;
  private productLineTextState: boolean = false;
  private chosepop:any;

  constructor(
    private http: HttphandleProvider,
    private loc: LocalstorageProvider,
    public toastCtrl: ToastController,
    protected route: Router,
    protected nativePageTransitions: NativePageTransitions,
    protected network: Network,
    private popoverCtrl: PopoverController,
    private events: Events
  ) {
    super(route, nativePageTransitions, network)
    this.defect = [];
    this.orderOne = {
      orderNumber: "",
      productName: "",
      planQuantity: "",
      fpy: "",
      doneQuantity: ""
    }

    this.orderTwo = {
      todayPlanQuantity: "",
      todayfpy: "",
      todayDoneQuantity: "",
      capacity: "",
      chartsNumb: [""],
      chartsTime: [""]
    };
    this.appGetProductionLineState();
    this.events.subscribe('choseres', data => {
      this.line = data
      this.getRrgionList()
    })
  }

  Refresh(refresher) {
    if (this.ProductionLine.state) {
      this.getDetailInfo(refresher);
      return false
    } else {
      refresher && refresher.complete();
    }
    this.appGetProductionLineState(refresher)


  }

  choselinemethod() {
    console.log('产线选择')
    var that = this
    this.chosepop = this.popoverCtrl.create(ChoselinePage, {
      title: '产线选择',
      datalists: that.AttendandceList
    }, {
      cssClass: 'choselinewraper',
      showBackdrop: true,
      enableBackdropDismiss: true
    });
    this.chosepop.present()

  }

  appGetProductionLineState(refresher?) {
    this
      .http
      .get('/app/rest/v2/services/yes_AppProductionMonitorService/appGetProductionLineState',)
      .then(res => {
        this.titleState = true;
        if (res.productLineState == false) {
          this.productLineState = res.productLineState;
          this.productLineTextState = true;
        } else {
          this.productLineState = true;
          this.AttendandceList = res.productionLine;
          this.ngAfterViewInitState = this.AttendandceList[0].id;
          this.ProductionLine = this.AttendandceList[0];
          this.lineState = this.AttendandceList[0].state;
          if (this.lineState == true) {
            this.getDetailInfo()
          }
        }
        refresher && refresher.complete();
      })
      .catch(err => {
        refresher && refresher.complete();
        if (err.status === 401) {
          this.http.getToken((res) => {
              this.loc.set('token', res.json());
              this.appGetProductionLineState()
            })
        } else {
          this.toastCtrl.create({
              message: err.errMsg || err,
              position: 'top',
              duration: 1000
            }).present()
        }
      });
  }

  getDetailInfo(refresher?){
    this.http.post('/app/rest/v2/services/yes_AppProductionMonitorService/pubAppMessage', {productionLineId: this.ngAfterViewInitState})
      .then(res => {
        if (res.error) {
          this.toastCtrl.create({
            message: res.error,
            position: 'top',
            duration: 1000
          }).present()
        } else {
          this.orderOne = res.order1;
          this.orderTwo = res.order2;
          this.defect = this.orderTwo.defect;
          var myChartData = this.myChartData(res);
          // 使用刚指定的配置项和数据显示图表。
          this.myChart.setOption(myChartData);
          this.myChart.resize();
        }
        refresher && refresher.complete();
      })
      .catch(err => {
        refresher && refresher.complete();
        if (err.status === 401) {
          this.http.getToken((res) => {
            this.loc.set('token', res.json());
            this.getDetailInfo(refresher)
          })
        } else {
          this.toastCtrl.create({
            message: err.errMsg || err,
            position: 'top',
            duration: 1000
          }).present()
        }
      })
  }

  presentToast(productLineState) {
    let toast = this
      .toastCtrl
      .create({message: productLineState, duration: 2000, position: "middle"});
    toast.present();
  }

  ngAfterViewInit() {
    this.creatEcharts();
  }

  ngOnDestroy(){
    this.events.unsubscribe('choseres')
  }

  creatEcharts() {
    this.myChart = ECharts.init(document.getElementById('main')as HTMLDivElement);
  }

  myChartData(res) {
    // 指定图表的配置项和数据
    var option = {
      xAxis: {
        boundaryGap: false,
        // data: ['00:00','01:00','02:00','03:00','04:00','05:00','06:00', '07:00',
        // '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00',
        // '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00',
        // '00:00']
        data: this.orderTwo.chartsTime
      },
      tooltip: {
        trigger: 'axis'
      },
      yAxis: {
        type: 'value',
        minInterval: 1
      },
      grid: {
        left: '7%',
        top: "9%",
        right: "4%"
      },
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0],
          start: 0,
          end: 50,
          startValue: 10,
          endValue: 100,
          filterMode: 'none',
          orient: 'horizontal',
          zoomOnMouseWheel: false
        }
      ],
      series: [
        {
          name: '产能(件)',
          type: 'line',
          label: {
            normal: {
              show: true
            }
          },
          // data:
          // ["12","21","18","12","21","18","12","21","18","12","21","18","12","21","18"],
          data: this.orderTwo.chartsNumb
        }
      ]
    };
    return option
  }

  getRrgionList() {
    this.ProductionLine = this.line;
    this.lineState = this.line.state;
    if (this.lineState !== false) {
      this
        .http
        .post('/app/rest/v2/services/yes_AppProductionMonitorService/pubAppMessage', {productionLineId: this.line.id})
        .then(res => {
          this.orderOne = res.order1;
          this.orderTwo = res.order2;
          var myChartData = this.myChartData(res);
          console.dir(myChartData)
          // 使用刚指定的配置项和数据显示图表。
          this
            .myChart
            .setOption(myChartData);
        })
    }
  }

  back() {
    this.goback()
  }
}
